package com.Lyy.dao;

import com.Lyy.UL.ICO;
import com.Lyy.enity.Student;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;

import java.sql.*;

@Data
public class StudentDao implements StudentDaoI{

    @Override
    public Student SelectStudentById(int id) {
        DruidDataSource dataSource = (new ICO()).ico("student.xml", DruidDataSource.class);
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from student.students where student_id ="+id);
            while (resultSet.next()){
                Student student = new Student(resultSet.getInt("student_id"),resultSet.getString("student_name"));
                if (connection !=null){
                    connection.close();
                }
                if (statement !=null){
                    statement.close();
                }
                if (resultSet !=null){
                    resultSet.close();
                }


                return student;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    @Override
    public int deleteStudentById(int id) {
        // 真实从数据库拿数据，通过druid连接池
        DruidDataSource dataSource = (new ICO()).ico("student.xml", DruidDataSource.class);
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            Statement st = connection.createStatement();
            int i = st.executeUpdate("delete from student.students where student_id = "+id);
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int addStudentById(Student student) {
        DruidDataSource dataSource = (new ICO()).ico("student.xml", DruidDataSource.class);
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            String sql = "insert into student.students (student_name) values (?)";
            PreparedStatement st = connection.prepareStatement(sql);
            st.setString(1, student.getStudentName());
            int i = st.executeUpdate();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
